package com.gome.bg.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.servlet.http.HttpSession;

@SuppressWarnings("rawtypes")
public class MySessionContext {

	private static MySessionContext instance;

	private HashMap mymap;
	private HashMap usermap;

	private MySessionContext() {
		mymap = new HashMap();
		usermap = new HashMap();
	}

	public static MySessionContext getInstance() {
		if (instance == null) {
			instance = new MySessionContext();
		}
		return instance;
	}

	@SuppressWarnings("unchecked")
	public synchronized void AddSession(HttpSession session) {
		if (session != null) {
			if (mymap.size() > 50) {
				Iterator iterator = mymap.keySet().iterator();
				while (iterator.hasNext()) {
					if (mymap.get(iterator.next()) == null) {
						mymap.remove(session.getId());
						usermap.remove(session.getId());
					}
				}
			}
			mymap.put(session.getId(), session);
		}
	}

	public synchronized void DelSession(HttpSession session) {
		if (session != null) {
			mymap.remove(session.getId());
		}
	}

	public synchronized HttpSession getSession(String session_id) {
		if (session_id == null)
			return null;
		return (HttpSession) mymap.get(session_id);
	}

	public synchronized void iteratesSession() {

		mymap.size();
		Iterator iterator = mymap.keySet().iterator();
		while (iterator.hasNext()) {
			System.out.println(mymap.get(iterator.next()));
		}
	}

	@SuppressWarnings("unchecked")
	public synchronized void AddUserSession(HttpSession session, String name) {
		if (session != null) {
			usermap.put(session.getId(), name);
		}
	}

	public synchronized void DelUseSession(HttpSession session) {
		if (session != null) {
			usermap.remove(session.getId());
		}
	}

	public synchronized String getUseSession(String session_id) {
		if (session_id == null)
			return null;
		return (String) usermap.get(session_id);
	}

	public synchronized boolean iteratesUseSession(String user) {
		boolean flag = false;
		if (usermap.size() == 0) {
			return flag;
		}
		@SuppressWarnings("unchecked")
		Set<String> key = usermap.keySet();
		for (Iterator it = key.iterator(); it.hasNext();) {
			String s = (String) it.next();
			if (usermap.get(s).equals(user)) {
				flag = true;
				break;
			}
			flag = false;
		}
		return flag;
	}

	public synchronized void iteratesUseSession() {

		usermap.size();
		Iterator iterator = usermap.keySet().iterator();
		while (iterator.hasNext()) {
			System.out.println(usermap.get(iterator.next()));
		}
	}
}
